package com.bw.controller;

import com.alibaba.fastjson.JSONObject;
import com.bw.entity.User;
import com.bw.service.UserService;
import org.spring.kun.common.GiteeUtils;
import org.spring.kun.common.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.SortedMap;

@Controller
public class GiteeBindController {

    @Autowired
    UserService userService;

    @RequestMapping("/callbackCode.do")
    public String callback(String code, HttpServletRequest request, HttpServletResponse response){
        System.out.println("接收到的临时授权码 " + code);
        String tokenByCode = GiteeUtils.getAccessTokenByCode(code);
        System.out.println("获取到的token " + tokenByCode);
        JSONObject userInfoByToken = GiteeUtils.getGiteeUserInfoByToken(tokenByCode);
        System.out.println("接收到的用户资料 " + userInfoByToken.toJSONString());

        // 获取  gitee账号里 三个字段   昵称 头像 giteeId

        String nickName = userInfoByToken.getString("name");
        String avatarUrl = userInfoByToken.getString("avatar_url");
        Integer giteeId = userInfoByToken.getInteger("id");

        // 获取当前登录用户  从cookie里获取token 再解密token
        User userFromRequest = TokenUtils.getLoginUserFromRequest(request, User.class);

        // 合并这两个账号信息
        userFromRequest.setGiteeId(giteeId);
        userFromRequest.setAvatarUrl(avatarUrl);
        userFromRequest.setNickName(nickName);

        userService.updateUserById(userFromRequest);


        // 重新加密一下用户 ，因为用户资料发生改变 需要重新制作token令牌
        TokenUtils.responseTokenByCookie(userFromRequest,response,30);


        return "redirect:list.do";

    }
}
